package com.cool.islife.service.impl;

import com.cool.islife.mapper.UserMapper;
import com.cool.islife.service.UserService;
import com.cool.islife.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * User: cool
 * Date: 2018/2/1
 * Time: 15:44
 *
 * key 生成策略是自己想的
 * 如果 redis 做缓存  key 的生成策略，得保证唯一，这样，get  update delete 才能操作缓存
 * 如果 ehcache 他的缓存是放到内存里面的，key可以不用考虑那么多，因为他操作的是对象。
 */
@CacheConfig(cacheNames = "voCache")
@Service
public class UserCashServiceImpl  implements UserService{

    public static final String USER_ALL_KEY = "#user_all";
    public static final String USER_CACHE_NAME = "user";
    @Autowired
    UserMapper userMapper;

    @Cacheable(key = "'"+USER_ALL_KEY+"' + #id.toString()",value = USER_CACHE_NAME)
    @Override
    public UserVO get(Long id) {
        System.out.println("查询功能，缓存找不到，直接读库, id=" + id);
        return userMapper.selectByPrimaryKey(id);
    }

    //wiselyKeyGenerator  是redis 自动生成Key 策略。(好像列表，一般不做缓存，这里做测试 )
    @Cacheable(keyGenerator="wiselyKeyGenerator",value = USER_CACHE_NAME)
    @Override
    public List<UserVO> list() {
        System.out.println("查询功能，缓存找不到，直接读库");
        return userMapper.selectAll();
    }

    @Override
    public int save(UserVO userVO) {
        return userMapper.insert(userVO);
    }

    @CachePut(key = "'"+USER_ALL_KEY+"' + #userVO.id.toString()",value = USER_CACHE_NAME)
    @Override
    public int update(UserVO userVO) {
        System.out.println("更新功能，更新缓存，直接写库, id=" + userVO);
        return userMapper.updateByPrimaryKey(userVO);
    }

    @CacheEvict(key = "'"+USER_ALL_KEY+"' + #id.toString()",value = USER_CACHE_NAME)
    @Override
    public int delete(Long id) {
        System.out.println("删除功能，删除缓存，直接写库, id=" + id);
        return userMapper.deleteByPrimaryKey(id);
    }
}
